// pages/cultivation/product/Source/source.js
const http = require("../../../../utils/request");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loaded:false,
    enable: false,
    loadingProps: {
      size: '40rpx',
    },
    backTopVisible: false,
    change_data:{},
    operation: 0,
    value:"",
    breed: "",
    count: 0,
    isin:false,
    isout:false,
    imgs:[],
    sate: 0,
    display: false,
    showImg: false,
    dateTwoVisible: false,
    dateTwo: new Date().getTime(), // 支持时间戳传入
    // 指定选择区间起始值
    start: "2000-01-01",
    end: "2030-09-09",
    fabButton: {
      icon: 'add',
      openType: 'add',
      theme: 'light',
    },
    inButton: {
      icon: 'add',
      openType: 'add',
      theme: 'light',
    },
    source: [],
    type: {
      name:"操作名称",
      people:"操作人",
      time:"操作时间"
    },
    intype: {
      people:"操作人",
      count: "入栏数量"
    }
  },
  onUpload(file) {
    const { imgs } = this.data;
    const { length } = imgs;
    this.setData({
      imgs: [...this.data.imgs,{...file,status:'loading'}],
      display: true
    });  
    const task = wx.uploadFile({
      url: 'https://37y5825u15.oicp.vip/admin/cos/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        this.setData({
          [`imgs[${length}].status`]: 'done',
          [`imgs[${length}].url`]: JSON.parse(res.data).data,
          [`change_data.picture[${length}]`]: JSON.parse(res.data).data,
          [`imgs[${length}].percent`]: res.progress,
          display: false,
        });
      },
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`imgs[${length}].percent`]: res.progress,
        [`imgs[${length}].status`]: 'loading',
      });
    });
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.onUpload(files[files.length-1]);
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { imgs } = this.data;
    imgs.splice(index, 1);
    let data = this.data.change_data
    data['picture'].splice(index,1)
    console.log('pic',data);
    this.setData({
      imgs,
      data
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  change(v) {
    let index = v.currentTarget.dataset.data
    let value = v.detail.value
    let data = this.data.change_data
    data[index] = value
    this.setData({
      data,
    })
  },
  handleChange(e) {
    const { value } = e.detail;
    this.setData({
      count: value
    });
    this.change(e)
  },
  unshow(e) {
    this.setData({
      showImg: e.detail
    })
  },
  ShowImg(e){
    this.setData({
      showImg: true,
      imgs: e.currentTarget.dataset.data
    })
  },
  cancel() {
    this.setData({
      operation:0,
    })
  },
  showPickerTwo(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`dateTwoVisible`]: true,
    });
  },
  hidePickerTwo() {
    const { mode } = this.data;
    this.setData({
      [`dateTwoVisible`]: false,
    });
  },
  onConfirmTwo(e) {
    const { value } = e.detail;
    const { mode } = this.data;
    console.log("confirm", value);
    let data = this.data.change_data
    data['createTime'] = value;
    data['time'] = value;
    this.setData({
      [mode]: value,
      data,
      value:value
    });
    console.log(this.data.value);
    this.hidePickerTwo();
  },
  onColumnChangeTwo(e) {
    console.log("pick", e.detail.value);
  },
  input(e) {
    this.setData({
      value: e.detail.value
    })
  },
  onUpload(file) {
    const { imgs } = this.data;
    const { length } = imgs;
    this.setData({
      imgs: [...imgs,{...file,status:'loading'}],
    });
    const task = wx.uploadFile({
      url: 'https://37y5825u15.oicp.vip/admin/cos/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        this.setData({
          [`imgs[${length}].status`]: 'done',
        });
        this.setData({
          [`change_data.picture[${length}]`]: JSON.parse(res.data).data,
        });
      },
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`imgs[${length}].percent`]: res.progress,
      });
    });
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.onUpload(files[files.length-1]);
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { imgs } = this.data;
    imgs.splice(index, 1);
    let data = this.data.change_data
    data['picture'].splice(index,1)
    this.setData({
      imgs,
      data
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  showadd(){
    this.setData({
      display: !this.data.display
    })
  },
  other() {
    this.onLoad()
    this.setData({
      operation: 4,
      change_data: {
        picture:[],
        cultivationCode: this.data.breed,
        name:"",
        people:"",
        time:"",
        parentField: "Cultivation",
      },
      imgs:[],
      display: false,
    })
  },
  put() {
    this.onLoad() //防止数据未加载到
    let count = getApp().globalData.farm_data;
    this.setData({
      operation: 3,
      change_data: {
        picture:[],
        cultivationCode: this.data.breed,
        parentField: "Cultivation",
        count: this.data.count || 0
      },
      imgs:[],
      display: false,
    })
  },
  add() {
    this.onLoad() //防止数据未加载到
    this.setData({
      operation: 2,
      change_data: {
        picture:[],
        cultivationCode: this.data.breed,
        parentField: "Cultivation",
      },
      imgs:[],
      display: false,
    })
  },
  onEdit(v) {
    let imgs = [];
    if(v.currentTarget.dataset.data['picture']) {
      for(let i = 0;i<v.currentTarget.dataset.data['picture'].length;i++) {
        imgs.push({
          name: v.currentTarget.dataset.data['picture'][i],
          url: v.currentTarget.dataset.data['picture'][i],
          type: 'image'
        })
      }
    }
    this.setData({
      operation: 1,
      change_data:v.currentTarget.dataset.data,
      value: v.currentTarget.dataset.data['time'],
      imgs: imgs
    })
  },
  load(){
    let data = getApp().globalData;
    let breed = data.codeing
    let datas = []
    http.getRequest('/admin/cultivation?code='+breed,{},res=>{
      this.setData({
        count: res.data.data.enclosureNumber || 0,
        max_count: res.data.data.enclosureNumber ||0
      })
      console.log("数量",this.data.count);
      if(res.data.data.state === "CREATED") {
        this.setData({
          isin: false,
          isout: true,
        })
      }
      else if(res.data.data.state === "ENCLOSURE") {
        this.setData({
          isin: true,
          isout: false,
        })
      }
      else if(res.data.data.state === "FATTENED") {
        this.setData({
          isin: true,
          isout: true,
        })
      }else{
        this.setData({
          isin: true,
          isout: true,
        })
      }
    },err=>{})
    http.getRequest('/admin/cultivation/'+breed+'/operation',{},res=>{
      datas = res.data.data
      this.setData({
        source: datas,
        op: data.operation,
        breed: breed,
      })
    },err=>{})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.load()
  },
  add_confirm(){
    let {operation} = this.data;
    console.log('add',this.data.change_data);
    if(operation===2){
      http.postRequestBody('/admin/traceability/enclosure',JSON.stringify(this.data.change_data),res=>{
        if(res.data.success===true){
          wx:wx.showToast({
            title: '入栏成功',
          })
          this.onLoad()
        }else{
          wx:wx.showToast({
            title: '重复入栏，失败！',
            icon: 'error'
          })
        }
      },err=>{
      })
    }else if(operation===3){
      http.postRequestBody('/admin/traceability/fatten',JSON.stringify(this.data.change_data),res=>{
        if(res.data.success===true){
          wx:wx.showToast({
            title: '出栏成功',
          })
          this.onLoad()
        }else{
          wx:wx.showToast({
            title: '重复出栏，失败！',
            icon: 'error'
          })
        }
      },err=>{
      })
    }else{
      http.postRequestBody('/admin/traceability/operation',JSON.stringify(this.data.change_data),res=>{
        if(res.data.success===true){
          wx:wx.showToast({
            title: '操作成功',
          })
          this.onLoad()
        }else{
          wx:wx.showToast({
            title: '失败！',
            icon: 'error'
          })
        }
      },err=>{
      })
    }
    console.log('add');
    this.onLoad()
    this.cancel()
  },
  confirm() {
    let {operation} = this.data
    if(operation===1){
      http.putRequest('/admin/traceability/operation',JSON.stringify(this.data.change_data),res=>{
        wx:wx.showToast({
          title: '修改成功',
        })
        this.onLoad()
      },err=>{})
    }
    else if(operation===4){
      console.log(this.data.change_data);
      http.postRequestBody('/admin/traceability/operation',JSON.stringify(this.data.change_data),res=>{
        if(res.data.success===true){
          wx:wx.showToast({
            title: '成功',
          })
          this.onLoad()
        }else{
          wx:wx.showToast({
            title: '失败！',
            icon: 'error'
          })
        }
      },err=>{
      })
    }
    this.cancel()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.load()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onRefresh() {
    new Promise((res,rej)=>{
      setTimeout(()=>{
        this.setData({
          loaded:true
        })
        res();
      },0);
    }).then((res)=>{
      setTimeout(()=>{
        this.setData({
          enable:true
        })
      },10)
    }).then(()=>{
      this.load();
    })
    .then(()=>{
      setTimeout(()=>{
        this.setData({
          enable:false,
        })
      },100);
    })
    .then((res)=>{
      setTimeout(()=>{
        this.setData({
          loaded:false
        })
      },500)
    });
  },
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({
      backTopVisible: scrollTop > 100,
    });
  },
})